const jwt = require('jsonwebtoken');
const utils = require('../../utils/utils');
const sqlPool = require('../../DB/sqlPool');
const sqlConfig = require('../../DB/sqlConfig');
const hashPassword = require('../../utils/setHash');
const verifyCode = require('../../utils/verifyCode');

// JWT密钥
const JWT_SECRET = 'h5_user_jwt_secret_key';
// Token有效期（秒）
const TOKEN_EXPIRATION = 60 * 60 * 24 * 7; // 7天

/**
 * 发送邮箱验证码
 */
async function sendEmailCode(req, res) {
    try {
        const { email, purpose } = req.body;
        
        if (!email) {
            return res.json(utils.ErrorResponse('邮箱不能为空'));
        }
        
        if (!purpose || !['register', 'login', 'reset'].includes(purpose)) {
            return res.json(utils.ErrorResponse('验证码用途不正确'));
        }
        
        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return res.json(utils.ErrorResponse('邮箱格式不正确'));
        }
        
        // 如果是注册，检查邮箱是否已注册
        if (purpose === 'register') {
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE email = ?`,
                [email]
            );
            
            if (rows && rows.length > 0) {
                return res.json(utils.ErrorResponse('该邮箱已注册'));
            }
        }
        
        // 如果是登录或重置密码，检查邮箱是否存在
        if (purpose === 'login' || purpose === 'reset') {
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE email = ?`,
                [email]
            );
            
            if (!rows || rows.length === 0) {
                return res.json(utils.ErrorResponse('该邮箱尚未注册'));
            }
        }
        
        // 发送验证码
        const result = await verifyCode.sendEmailCode(email, purpose);
        
        if (!result.success) {
            return res.json(utils.ErrorResponse('验证码发送失败: ' + result.message));
        }
        
        return res.json(utils.SuccessResponse({
            message: '验证码发送成功'
        }));
    } catch (error) {
        console.error('发送邮箱验证码失败:', error);
        return res.json(utils.ErrorResponse('发送邮箱验证码失败'));
    }
}

/**
 * 发送短信验证码
 */
async function sendSMSCode(req, res) {
    try {
        const { phone, purpose } = req.body;
        
        if (!phone) {
            return res.json(utils.ErrorResponse('手机号不能为空'));
        }
        
        if (!purpose || !['register', 'login', 'reset'].includes(purpose)) {
            return res.json(utils.ErrorResponse('验证码用途不正确'));
        }
        
        // 验证手机号格式（中国大陆手机号）
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(phone)) {
            return res.json(utils.ErrorResponse('手机号格式不正确'));
        }
        
        // 如果是注册，检查手机号是否已注册
        if (purpose === 'register') {
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE phone = ?`,
                [phone]
            );
            
            if (rows && rows.length > 0) {
                return res.json(utils.ErrorResponse('该手机号已注册'));
            }
        }
        
        // 如果是登录或重置密码，检查手机号是否存在
        if (purpose === 'login' || purpose === 'reset') {
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE phone = ?`,
                [phone]
            );
            
            if (!rows || rows.length === 0) {
                return res.json(utils.ErrorResponse('该手机号尚未注册'));
            }
        }
        
        // 发送验证码
        const result = await verifyCode.sendSMSCode(phone, purpose);
        
        if (!result.success) {
            return res.json(utils.ErrorResponse('验证码发送失败: ' + result.message));
        }
        
        return res.json(utils.SuccessResponse({
            message: '验证码发送成功'
        }));
    } catch (error) {
        console.error('发送短信验证码失败:', error);
        return res.json(utils.ErrorResponse('发送短信验证码失败'));
    }
}

/**
 * 用户注册
 */
async function register(req, res) {
    try {
        const { username, password, confirmPassword, email, phone, code, type } = req.body;
        
        // 基本验证
        if (!username) {
            return res.json(utils.ErrorResponse('用户名不能为空'));
        }
        
        if (!password) {
            return res.json(utils.ErrorResponse('密码不能为空'));
        }
        
        if (password !== confirmPassword) {
            return res.json(utils.ErrorResponse('两次密码输入不一致'));
        }
        
        if (password.length < 6) {
            return res.json(utils.ErrorResponse('密码长度不能少于6位'));
        }
        
        if (!type || !['email', 'phone'].includes(type)) {
            return res.json(utils.ErrorResponse('注册类型不正确'));
        }
        
        if (!code) {
            return res.json(utils.ErrorResponse('验证码不能为空'));
        }
        
        // 根据注册类型验证
        if (type === 'email') {
            if (!email) {
                return res.json(utils.ErrorResponse('邮箱不能为空'));
            }
            
            // 验证邮箱格式
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                return res.json(utils.ErrorResponse('邮箱格式不正确'));
            }
            
            // 检查邮箱是否已注册
            const { rows: emailCheck } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE email = ?`,
                [email]
            );
            
            if (emailCheck && emailCheck.length > 0) {
                return res.json(utils.ErrorResponse('该邮箱已注册'));
            }
            
            // 验证验证码
            const isCodeValid = await verifyCode.verifyCode('email', email, code, 'register');
            if (!isCodeValid) {
                return res.json(utils.ErrorResponse('验证码无效或已过期'));
            }
        } else if (type === 'phone') {
            if (!phone) {
                return res.json(utils.ErrorResponse('手机号不能为空'));
            }
            
            // 验证手机号格式
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(phone)) {
                return res.json(utils.ErrorResponse('手机号格式不正确'));
            }
            
            // 检查手机号是否已注册
            const { rows: phoneCheck } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE phone = ?`,
                [phone]
            );
            
            if (phoneCheck && phoneCheck.length > 0) {
                return res.json(utils.ErrorResponse('该手机号已注册'));
            }
            
            // 验证验证码
            const isCodeValid = await verifyCode.verifyCode('phone', phone, code, 'register');
            if (!isCodeValid) {
                return res.json(utils.ErrorResponse('验证码无效或已过期'));
            }
        }
        
        // 检查用户名是否已注册
        const { rows: usernameCheck } = await sqlPool.queryData(
            `SELECT * FROM shequ_users WHERE username = ?`,
            [username]
        );
        
        if (usernameCheck && usernameCheck.length > 0) {
            return res.json(utils.ErrorResponse('该用户名已被使用'));
        }
        
        // 密码加密
        const passwordData = hashPassword.saltHashPassword(password);
        
        // 插入用户记录
        const userData = {
            username,
            password: passwordData.passwordHash,
            salt: passwordData.salt,
            email: type === 'email' ? email : null,
            phone: type === 'phone' ? phone : null,
            status: 1,
            created_at: new Date(),
            updated_at: new Date()
        };
        
        const { rows } = await sqlPool.queryData(
            `INSERT INTO shequ_users SET ?`,
            userData
        );
        
        if (!rows || !rows.insertId) {
            return res.json(utils.ErrorResponse('注册失败'));
        }
        
        // 生成token
        const token = jwt.sign(
            { id: rows.insertId, username },
            JWT_SECRET,
            { expiresIn: TOKEN_EXPIRATION }
        );
        
        return res.json(utils.SuccessResponse({
            token,
            user: {
                id: rows.insertId,
                username,
                email: type === 'email' ? email : null,
                phone: type === 'phone' ? phone : null,
                created_at: userData.created_at
            }
        }));
    } catch (error) {
        console.error('注册失败:', error);
        return res.json(utils.ErrorResponse('注册失败'));
    }
}

/**
 * 密码登录
 */
async function loginByPassword(req, res) {
    try {
        const { account, password } = req.body;
        
        if (!account) {
            return res.json(utils.ErrorResponse('账号不能为空'));
        }
        
        if (!password) {
            return res.json(utils.ErrorResponse('密码不能为空'));
        }
        
        // 查询用户（支持用户名、邮箱、手机号登录）
        const { rows } = await sqlPool.queryData(
            `SELECT * FROM shequ_users WHERE username = ? OR email = ? OR phone = ?`,
            [account, account, account]
        );
        
        if (!rows || rows.length === 0) {
            return res.json(utils.ErrorResponse('账号或密码错误'));
        }
        
        const user = rows[0];
        
        // 检查用户状态
        if (user.status !== 1) {
            return res.json(utils.ErrorResponse('账号已被禁用'));
        }
        
        // 验证密码
        const hashedPassword = hashPassword.checkPassword(password, user.salt);
        if (hashedPassword !== user.password) {
            return res.json(utils.ErrorResponse('账号或密码错误'));
        }
        
        // 更新登录信息
        await sqlPool.queryData(
            `UPDATE shequ_users SET 
             last_login_time = NOW(), 
             last_login_ip = ?, 
             login_count = login_count + 1 
             WHERE id = ?`,
            [req.ip, user.id]
        );
        
        // 生成token
        const token = jwt.sign(
            { id: user.id, username: user.username },
            JWT_SECRET,
            { expiresIn: TOKEN_EXPIRATION }
        );
        
        // 返回用户信息（不包含敏感信息）
        const userInfo = {
            id: user.id,
            username: user.username,
            email: user.email,
            phone: user.phone,
            avatar: user.avatar,
            created_at: user.created_at
        };
        
        return res.json(utils.SuccessResponse({
            token,
            user: userInfo
        }));
    } catch (error) {
        console.error('登录失败:', error);
        return res.json(utils.ErrorResponse('登录失败'));
    }
}

/**
 * 验证码登录
 */
async function loginByCode(req, res) {
    try {
        const { account, code, type } = req.body;
        
        if (!account) {
            return res.json(utils.ErrorResponse('账号不能为空'));
        }
        
        if (!code) {
            return res.json(utils.ErrorResponse('验证码不能为空'));
        }
        
        if (!type || !['email', 'phone'].includes(type)) {
            return res.json(utils.ErrorResponse('登录类型不正确'));
        }
        
        // 查询用户
        let user;
        if (type === 'email') {
            // 验证邮箱格式
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(account)) {
                return res.json(utils.ErrorResponse('邮箱格式不正确'));
            }
            
            // 验证验证码
            const isCodeValid = await verifyCode.verifyCode('email', account, code, 'login');
            if (!isCodeValid) {
                return res.json(utils.ErrorResponse('验证码无效或已过期'));
            }
            
            // 查询用户
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE email = ?`,
                [account]
            );
            
            if (!rows || rows.length === 0) {
                return res.json(utils.ErrorResponse('账号不存在'));
            }
            
            user = rows[0];
        } else if (type === 'phone') {
            // 验证手机号格式
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(account)) {
                return res.json(utils.ErrorResponse('手机号格式不正确'));
            }
            
            // 验证验证码
            const isCodeValid = await verifyCode.verifyCode('phone', account, code, 'login');
            if (!isCodeValid) {
                return res.json(utils.ErrorResponse('验证码无效或已过期'));
            }
            
            // 查询用户
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE phone = ?`,
                [account]
            );
            
            if (!rows || rows.length === 0) {
                return res.json(utils.ErrorResponse('账号不存在'));
            }
            
            user = rows[0];
        }
        
        // 检查用户状态
        if (user.status !== 1) {
            return res.json(utils.ErrorResponse('账号已被禁用'));
        }
        
        // 更新登录信息
        await sqlPool.queryData(
            `UPDATE shequ_users SET 
             last_login_time = NOW(), 
             last_login_ip = ?, 
             login_count = login_count + 1 
             WHERE id = ?`,
            [req.ip, user.id]
        );
        
        // 生成token
        const token = jwt.sign(
            { id: user.id, username: user.username },
            JWT_SECRET,
            { expiresIn: TOKEN_EXPIRATION }
        );
        
        // 返回用户信息（不包含敏感信息）
        const userInfo = {
            id: user.id,
            username: user.username,
            email: user.email,
            phone: user.phone,
            avatar: user.avatar,
            created_at: user.created_at
        };
        
        return res.json(utils.SuccessResponse({
            token,
            user: userInfo
        }));
    } catch (error) {
        console.error('登录失败:', error);
        return res.json(utils.ErrorResponse('登录失败'));
    }
}

/**
 * 重置密码
 */
async function resetPassword(req, res) {
    try {
        const { account, code, password, confirmPassword, type } = req.body;
        
        if (!account) {
            return res.json(utils.ErrorResponse('账号不能为空'));
        }
        
        if (!code) {
            return res.json(utils.ErrorResponse('验证码不能为空'));
        }
        
        if (!password) {
            return res.json(utils.ErrorResponse('密码不能为空'));
        }
        
        if (password !== confirmPassword) {
            return res.json(utils.ErrorResponse('两次密码输入不一致'));
        }
        
        if (password.length < 6) {
            return res.json(utils.ErrorResponse('密码长度不能少于6位'));
        }
        
        if (!type || !['email', 'phone'].includes(type)) {
            return res.json(utils.ErrorResponse('重置类型不正确'));
        }
        
        // 查询用户
        let user;
        if (type === 'email') {
            // 验证邮箱格式
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(account)) {
                return res.json(utils.ErrorResponse('邮箱格式不正确'));
            }
            
            // 验证验证码
            const isCodeValid = await verifyCode.verifyCode('email', account, code, 'reset');
            if (!isCodeValid) {
                return res.json(utils.ErrorResponse('验证码无效或已过期'));
            }
            
            // 查询用户
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE email = ?`,
                [account]
            );
            
            if (!rows || rows.length === 0) {
                return res.json(utils.ErrorResponse('账号不存在'));
            }
            
            user = rows[0];
        } else if (type === 'phone') {
            // 验证手机号格式
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(account)) {
                return res.json(utils.ErrorResponse('手机号格式不正确'));
            }
            
            // 验证验证码
            const isCodeValid = await verifyCode.verifyCode('phone', account, code, 'reset');
            if (!isCodeValid) {
                return res.json(utils.ErrorResponse('验证码无效或已过期'));
            }
            
            // 查询用户
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE phone = ?`,
                [account]
            );
            
            if (!rows || rows.length === 0) {
                return res.json(utils.ErrorResponse('账号不存在'));
            }
            
            user = rows[0];
        }
        
        // 密码加密
        const passwordData = hashPassword.saltHashPassword(password);
        
        // 更新密码
        await sqlPool.queryData(
            `UPDATE shequ_users SET 
             password = ?, 
             salt = ?, 
             updated_at = NOW() 
             WHERE id = ?`,
            [passwordData.passwordHash, passwordData.salt, user.id]
        );
        
        return res.json(utils.SuccessResponse('密码重置成功'));
    } catch (error) {
        console.error('重置密码失败:', error);
        return res.json(utils.ErrorResponse('重置密码失败'));
    }
}

/**
 * 获取用户信息
 */
async function getUserInfo(req, res) {
    try {
        // 获取当前登录用户信息
        const { id } = req.user;
        
        const { rows } = await sqlPool.queryData(
            `SELECT id, username, email, phone, avatar, status, last_login_time, 
             last_login_ip, login_count, created_at, updated_at 
             FROM shequ_users WHERE id = ?`,
            [id]
        );
        
        if (!rows || rows.length === 0) {
            return res.json(utils.ErrorResponse('用户不存在'));
        }
        
        return res.json(utils.SuccessResponse(rows[0]));
    } catch (error) {
        console.error('获取用户信息失败:', error);
        return res.json(utils.ErrorResponse('获取用户信息失败'));
    }
}

/**
 * 更新用户信息
 */
async function updateUserInfo(req, res) {
    try {
        // 获取当前登录用户ID
        const { id } = req.user;
        const { username, avatar } = req.body;
        
        const updateData = {};
        
        if (username) {
            // 检查用户名是否已被使用
            const { rows } = await sqlPool.queryData(
                `SELECT * FROM shequ_users WHERE username = ? AND id != ?`,
                [username, id]
            );
            
            if (rows && rows.length > 0) {
                return res.json(utils.ErrorResponse('该用户名已被使用'));
            }
            
            updateData.username = username;
        }
        
        if (avatar) {
            updateData.avatar = avatar;
        }
        
        if (Object.keys(updateData).length === 0) {
            return res.json(utils.ErrorResponse('没有要更新的内容'));
        }
        
        updateData.updated_at = new Date();
        
        // 更新用户信息
        await sqlPool.queryData(
            `UPDATE shequ_users SET ? WHERE id = ?`,
            [updateData, id]
        );
        
        return res.json(utils.SuccessResponse('更新成功'));
    } catch (error) {
        console.error('更新用户信息失败:', error);
        return res.json(utils.ErrorResponse('更新用户信息失败'));
    }
}

/**
 * H5后台管理 - 获取用户列表
 */
async function getUserList(req, res) {
    try {
        const { page = 1, limit = 10, username, email, phone, status } = req.query;
        
        // 构建查询条件
        let sql = `SELECT id, username, email, phone, avatar, status, last_login_time, 
                  last_login_ip, login_count, created_at, updated_at 
                  FROM shequ_users WHERE 1=1`;
        const params = [];
        
        if (username) {
            sql += ` AND username LIKE ?`;
            params.push(`%${username}%`);
        }
        
        if (email) {
            sql += ` AND email LIKE ?`;
            params.push(`%${email}%`);
        }
        
        if (phone) {
            sql += ` AND phone LIKE ?`;
            params.push(`%${phone}%`);
        }
        
        if (status !== undefined) {
            sql += ` AND status = ?`;
            params.push(status);
        }
        
        // 计算总数
        const countSql = sql.replace('SELECT id, username, email, phone, avatar, status, last_login_time, \n                  last_login_ip, login_count, created_at, updated_at', 'SELECT COUNT(*) as total');
        const { rows: countRows } = await sqlPool.queryData(countSql, params);
        const total = countRows && countRows.length > 0 ? countRows[0].total : 0;
        
        // 分页
        sql += ` ORDER BY id DESC LIMIT ?, ?`;
        params.push((page - 1) * limit, parseInt(limit));
        
        const { rows } = await sqlPool.queryData(sql, params);
        
        return res.json(utils.SuccessResponse({
            list: rows,
            total,
            page: parseInt(page),
            limit: parseInt(limit)
        }));
    } catch (error) {
        console.error('获取用户列表失败:', error);
        return res.json(utils.ErrorResponse('获取用户列表失败'));
    }
}

/**
 * H5后台管理 - 更新用户状态
 */
async function updateUserStatus(req, res) {
    try {
        const { id, status } = req.body;
        
        if (!id) {
            return res.json(utils.ErrorResponse('用户ID不能为空'));
        }
        
        if (status === undefined || ![0, 1].includes(Number(status))) {
            return res.json(utils.ErrorResponse('状态值不正确'));
        }
        
        // 检查用户是否存在
        const { rows } = await sqlPool.queryData(
            `SELECT * FROM shequ_users WHERE id = ?`,
            [id]
        );
        
        if (!rows || rows.length === 0) {
            return res.json(utils.ErrorResponse('用户不存在'));
        }
        
        // 更新用户状态
        await sqlPool.queryData(
            `UPDATE shequ_users SET status = ? WHERE id = ?`,
            [status, id]
        );
        
        // 记录操作日志
        const operationLog = {
            admin_user_id: req.user.id,
            user_name: req.user.username,
            operation_type: utils.OPERATION_TYPE.UPDATE,
            operation_content: `${Number(status) === 1 ? '启用' : '禁用'}H5用户: ${rows[0].username}`,
            create_time: new Date()
        };
        
        await sqlPool.queryData(
            `INSERT INTO ${sqlConfig.configureName.OPERATION_LOG} SET ?`,
            operationLog
        );
        
        return res.json(utils.SuccessResponse('更新成功'));
    } catch (error) {
        console.error('更新用户状态失败:', error);
        return res.json(utils.ErrorResponse('更新用户状态失败'));
    }
}

module.exports = {
    sendEmailCode,
    sendSMSCode,
    register,
    loginByPassword,
    loginByCode,
    resetPassword,
    getUserInfo,
    updateUserInfo,
    getUserList,
    updateUserStatus
}; 